package edu.rpi.tw.pml.browsing.client;

import java.util.ArrayList;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;

public class TableDataWidget {

	private final InstanceTableWidget instanceTable;
	private Command pendingRefresh;
	private InstanceTableDataProvider provider = new DataProvider();

	// Default constructor.
	public TableDataWidget() {
		instanceTable = new InstanceTableWidget(provider);
	}

	public void setPredicateValue(final String predicate, final String value) {
		// if (predicate.equals("")) {
		// // instanceTable.refresh("", "");
		// }
		//
		// if (pendingRefresh == null) {
		// pendingRefresh = new Command() {
		// public void execute() {
		// pendingRefresh = null;
		// instanceTable.refresh(predicate, value);
		// }
		// };
		// DeferredCommand.addCommand(pendingRefresh);
		// }
	}

	public void setConcepts(ArrayList<String> concepts) {
		// MessageBox
		// .alert("inside TableDataWidget.setConceptS(): " + concepts[0]);

		provider.setConceptList(concepts);
		if (pendingRefresh == null) {
			pendingRefresh = new Command() {
				public void execute() {
					pendingRefresh = null;
					instanceTable.refresh();
				}
			};
			DeferredCommand.addCommand(pendingRefresh);
		}
	}

	public Panel getPanel() {
		return instanceTable.getPanel();
	}

	/*
	 * Inner class to implement provider class.
	 */
	public class DataProvider implements InstanceTableDataProvider {

		private final FacetSearchServiceAsync proxy;
		private ArrayList<String> conceptList = new ArrayList<String>();

		public DataProvider() {
			proxy = (FacetSearchServiceAsync) GWT
					.create(FacetSearchService.class);
			ServiceDefTarget target = (ServiceDefTarget) proxy;
			String moduleRelativeURL = GWT.getModuleBaseURL() + "facetedSearch";
			target.setServiceEntryPoint(moduleRelativeURL);
		}

		public void updateTable(final TableDataAcceptor acceptor) {
			// Get updated instance lists via remote SPARQL endpoint.
			proxy.getInstances(conceptList, new AsyncCallback<String>() {
				public void onFailure(Throwable caught) {
					acceptor.failed(caught);
				}

				public void onSuccess(String result) {
					pushResults(acceptor, result);
				}
			});
		}

		public void setConceptList(ArrayList<String> conceptList) {
			this.conceptList = conceptList;
		}

		private void pushResults(TableDataAcceptor acceptor, String result) {
			acceptor.accept(result);
		}
	}
}
